﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLC
{
    class ModBusRTUManager
    {
        private static ModBusRTUManager modBusRTUManager = null;
        private static ModbusSerialMaster master = null;
        private static SerialPort port=null;
        /*private static String _portName = "COM1";
        private static int _baudRate = 9600;
        private static Parity _parity = Parity.None;
        private static ushort _dataBits = 8;
        private static StopBits _stopBits = StopBits.One;
        private static int _readTimeOut = 3000;*/

        private ModBusRTUManager()
        {

        }


        public static ModBusRTUManager GetInstance(String portName,int baudRate, Parity parity,ushort dataBits, StopBits stopBits,int readTimeOut)
        {
             /*_portName = portName;
             _baudRate = baudRate;
             _parity = parity;
            _dataBits = dataBits;
            _stopBits = stopBits;*/

            if (modBusRTUManager == null)
            {               
                port = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
                port.ReadTimeout = readTimeOut;
                master = ModbusSerialMaster.CreateRtu(port);
                modBusRTUManager = new ModBusRTUManager();
            }
            return modBusRTUManager;
        }

        private Boolean isOpen = false;

        public bool IsOpen { get => isOpen; set => isOpen = value; }


        public void Open()
        {
            if (!isOpen)
            {
                port.Open();
                isOpen = true;
            }
        }

        public void Close()
        {
            if (isOpen)
            {
                port.Close();
                isOpen = false;
            }
        }


        public ushort[] ReadHoldingRegisters(byte slaveAddress,ushort startAddress, ushort numberOfPoints)
        {
            ushort[] registerBuffer;            
            registerBuffer = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
           
            return registerBuffer;
        }

       

    
    }
}
